async function importPrivateKey(pem) {
  // 保持原有实现不变
  const pemHeader = "-----BEGIN PRIVATE KEY-----";
  const pemFooter = "-----END PRIVATE KEY-----";
  const pemContents = pem.replace(pemHeader, '').replace(pemFooter, '').replace(/\s/g, '');
  const binaryDer = Uint8Array.from(atob(pemContents), c => c.charCodeAt(0));
  
  return crypto.subtle.importKey(
    "pkcs8",
    binaryDer,
    { name: "RSA-OAEP", hash: "SHA-256" },
    true,
    ["decrypt"]
  );
}

self.onmessage = async (e) => {
  const { privateKeyPem, encryptedBase64 } = e.data;
  try {
      console.time('worker')
      const privateKey = await importPrivateKey(privateKeyPem);
      const encryptedData = Uint8Array.from(atob(encryptedBase64), c => c.charCodeAt(0));
      
      // 调整分片大小为256字节（适配2048位密钥）
      // 密钥是1024位，故分片大小事128
      const chunkSize = 128;
      const chunks = [];
      
      // 创建所有分片
      for (let i = 0; i < encryptedData.length; i += chunkSize) {
          chunks.push(encryptedData.slice(i, i + chunkSize));
      }
      
      // 并行解密所有分片
      const decryptedChunks = await Promise.all(
          chunks.map(chunk => 
              crypto.subtle.decrypt({ name: "RSA-OAEP" }, privateKey, chunk)
              .then(decrypted => new Uint8Array(decrypted))
          )
      );
      
      // 合并结果（优化合并逻辑）
      const merged = new Uint8Array(
          decryptedChunks.reduce((acc, arr) => acc + arr.length, 0)
      );
      let offset = 0;
      for (const arr of decryptedChunks) {
          merged.set(arr, offset);
          offset += arr.length;
      }
      
      self.postMessage({ result: new TextDecoder().decode(merged) });
      console.timeEnd('worker')
  } catch (err) {
      self.postMessage({ error: err.message });
  }
};